package v1

import (
	"blog/errmsg"
	"blog/model"
	"blog/utils"
	myvalidate "blog/validate"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)
func AddUser(c *gin.Context){
	var user model.User
	err := c.ShouldBindJSON(&user)
	if err!=nil {
		utils.HttpResponse(c,http.StatusOK,errmsg.BIND_DATA_FAIL,err.Error(),user)
	}else {
		msg,code := myvalidate.Validate(&user)
		if code == errmsg.SUCCESS{
			code,msg := model.CreateUser(&user)
			utils.HttpResponse(c,http.StatusOK,code,msg,user)
		}else {
			utils.HttpResponse(c,http.StatusOK,errmsg.FAIL,msg,user)
		}
	}
}
func GetUser(c *gin.Context){
	id,err := strconv.Atoi(c.Param("id"))
	if err!=nil {
		utils.HttpResponse(c,http.StatusOK,errmsg.PARAMS_TYPE_ERROR,err.Error(),nil)
	}else {
		code,msg,user := model.GetUser(id)
		utils.HttpResponse(c,http.StatusOK,code,msg,user)
	}
}
func GetUsers(c *gin.Context){
	page,_ := strconv.Atoi(c.Query("page"))
	pagesize,_ :=strconv.Atoi(c.Query("pagesize"))
	if page==0 {
		page = -1
	}
	if pagesize==0 {
		pagesize = -1
	}
	code,msg,users,total := model.GetUsers(page,pagesize)
	utils.HttpResponseTotal(c,http.StatusOK,code,msg,users,total)
}
func UpdateUser(c *gin.Context){
	id,err := strconv.Atoi(c.Param("id"))
	if err!=nil {
		utils.HttpResponse(c,http.StatusOK,errmsg.PARAMS_TYPE_ERROR,err.Error(),nil)
	}else {
		var user model.User //var相当于:=短变量定义声明并初始化对象
		user.ID = uint(id)
		err := c.ShouldBindJSON(&user)
		if err!=nil {
			utils.HttpResponse(c,http.StatusOK,errmsg.PARAMS_TYPE_ERROR,err.Error(),user)
		}else {
			code,msg := model.UpdateUser(user)
			utils.HttpResponse(c,http.StatusOK,code,msg,user)
		}
	}
}
func DeleteUser(c *gin.Context){
	id,err := strconv.Atoi(c.Param("id"))
	if err!=nil {
		utils.HttpResponse(c,http.StatusOK,errmsg.PARAMS_TYPE_ERROR,err.Error(),nil)
	}else {
		user := model.User{}
		user.ID = uint(id)
		code,msg:= model.DeleteUser(&user)
		utils.HttpResponse(c,http.StatusOK,code,msg,nil)
	}
}
